//
//  ProductViewController.m
//  片刻
//
//  Created by admin on 15/6/3.
//  Copyright (c) 2015年 iApple. All rights reserved.
//

#import "ProductViewController.h"
#import "ProductMainTableViewCell.h"
#import "ProductViewModel.h"
#import "MacroHeader.h"
#import "MJRefresh.h"

@interface ProductViewController ()
@property(nonatomic,retain)UITableView *mainTabelView;
@property(nonatomic,retain)NSMutableArray *dataSourceArray;
@property(nonatomic,assign)NSInteger totalProduct;
@property(nonatomic,assign)RequestDataType requestDataType;
@property(nonatomic,assign)BOOL isFirstRequest;

@end

@implementation ProductViewController

- (void)dealloc
{
    [_mainTabelView release];
    [_dataSourceArray release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor blackColor];
    _isFirstRequest = YES;
    [self requestDataWithStartRow:0];
 
    [self createMainTableView];
    
}

-(void)viewWillAppear:(BOOL)animated
{
    BOOL night = [[NSUserDefaults standardUserDefaults] boolForKey:@"night"];
    if (night) {
        self.view.backgroundColor = ESColor(50, 50, 50);
    }else{
        self.view.backgroundColor = [UIColor whiteColor];
    }
    [self.mainTabelView reloadData];
}

- (void)requestDataWithStartRow:(NSInteger)startRow {
    RequestManager *request = [[RequestManager alloc] initWithRequestURL:@"http://api2.pianke.me/pub/shop" requestModel:POST requestParameter:nil];
    NSString *startString = [NSString stringWithFormat:@"%ld",(long)startRow];
    NSMutableDictionary *mDict = [@{@"start":startString,@"client":@"1",@"deviceid":@"63A94D37-33F9-40FF-9EBB-481182338873",@"limit":@"10",@"auth":@"",@"version":@"3.0.2"} mutableCopy];
    request.parameterDic = mDict;

    request.delegate = self;
    [request startRequest];
    [request release];
    [mDict release];
}

- (void)createMainTableView {
    _mainTabelView = [[UITableView alloc] initWithFrame:CGRectMake(0, ZERO, SCREEN_WIDTH, SCREEN_HEIGHT - BAR_HEIGHT) style:(UITableViewStylePlain)];
    _mainTabelView.delegate = self;
    _mainTabelView.dataSource = self;
    [_mainTabelView registerClass:[ProductMainTableViewCell class] forCellReuseIdentifier:@"productCell"];
    _dataSourceArray = [[NSMutableArray alloc] initWithCapacity:0];
    // 添加传统的下拉刷新
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    [_mainTabelView addLegendHeaderWithRefreshingBlock:^{
        [self loadNewData];
    }];
    
    [_mainTabelView addLegendFooterWithRefreshingBlock:^{
        [self loadMoreData];
    }];
    self.mainTabelView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_mainTabelView];
}

#pragma mark - 网络请求

//请求完毕后让代理对象执行的方法，同时把请求完的data传给代理对象
- (void)requestDidFinishWithData:(NSData *)data {
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
    NSDictionary *dataDic = dic[@"data"];
    _totalProduct = [dataDic[@"total"] integerValue];
    NSArray *listArray = dataDic[@"list"];
    
//    if (_requestDataType == kRequestDataNew) {
//        [_dataSourceArray removeAllObjects];
//    }
    
    NSInteger idx = 0;
    for (NSDictionary *modelDic in listArray) {
        ProductViewModel *model = [[ProductViewModel alloc] init];
        [model setValuesForKeysWithDictionary:modelDic];
        
        if (_requestDataType == kRequestDataNew && !_isFirstRequest && idx < _dataSourceArray.count) {
            [_dataSourceArray replaceObjectAtIndex:idx withObject:model];
        } else {
            [_dataSourceArray addObject:model];
        }
        
        [model release];
        idx++;
    }
    _isFirstRequest = NO;
    
    [self.mainTabelView reloadData];
    
    // 拿到当前的下拉刷新控件，结束刷新状态
    [_mainTabelView.header endRefreshing];
    [_mainTabelView.footer endRefreshing];
    
}



//请求失败后把错误原因传给代理对象
- (void)requestError:(NSError *)error{
    
}

#pragma mark - TableView方法

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [_dataSourceArray count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return 40 * kVertical;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    ProductMainTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"productCell" forIndexPath:indexPath];
    ProductViewModel *model = _dataSourceArray[indexPath.row];
    cell.model = model;
    return cell;
   
}

#pragma mark - RefreshData


- (void)loadNewData
{
     _requestDataType = kRequestDataNew;
    [self requestDataWithStartRow:0];
    
}


- (void) loadMoreData
{   _requestDataType = kRequestDataMore;
    NSInteger countOfProduct = [_dataSourceArray count];
    if (countOfProduct < _totalProduct) {
        [self requestDataWithStartRow:countOfProduct];
    } else {
        //效果1:没有更多数据显示"No more data"
        //[_mainTabelView.footer noticeNoMoreData];
        //[_mainTabelView.footer setTitle:@"No more data" forState:MJRefreshFooterStateNoMoreData];
        
        //效果2: 没有数据可以继续上拉，但没有任何内容在底部显示
        [_mainTabelView.footer setTitle:@"" forState:MJRefreshFooterStateIdle];
        [_mainTabelView.footer endRefreshing];
    }
}


@end
